﻿/**
* @description  Tweens an image of noise in or out over an image, similar to a TV snow effect.
*/
package com.foed.animation.transitions {

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.utils.getTimer;
	
	import com.foed.events.TweenEvent;
	
	public class NoiseTransition extends Transition {
	
		private var _noiseImage:BitmapData;
		private var _noiseHolder:Sprite;
		private var _fade:FadeTransition;
		
		/**
		* @description  Constructor.
		*
		* @param  pClip  The clip on which to perform the transition.
		* @param  pStartTransform  The starting values for the color transition.
		* @param  pEndTransform  The destination values for the color transition.
		* @param  pTime  The length in milliseconds for the transition.
		* @param  pType  The type of transition. IN moves from startTransform to endTransfom. OUT does the opposite.
		* @param  pEaseFunction  The function to use to transform the transition values over time.
		*/
		public function NoiseTransition(
			pClip:DisplayObject=null,
			pStartTransform:Object=null,
			pEndTransform:Object=null,
			pTime:Number=1000,
			pType:String=null,
			pEaseFunction:Function=null
		) {
			super(pClip, pTime, 0, 1, pType, pEaseFunction);
		}
	
		/**
		* @description  Called each iteration of the tween by the TweenRunner to transform values.
		*
		* @param  pChangeValues  The current values of the transition at each iteration of the tween.
		*/
		override protected function runTransition(pChangeValues:Object):void {
			_noiseImage.noise(getTimer(), 0, 255, 7, true);
			super.runTransition(pChangeValues);
		}
		
		/**
		* @description  Prepares clip to have transitions applied by adding new parent clip.
		*/
		override protected function prepare():void {
			super.prepare();
			_noiseImage = new BitmapData(clip.width, clip.height, true, 0x00FFFFFF);
			var pNoise:Bitmap = new Bitmap(_noiseImage);
			_noiseHolder = new Sprite();
			_noiseHolder.addChild(pNoise);
			_clipHolder.addChild(_noiseHolder);
		}
	
		/**
		* @description  Removes any artifacts of the transition.
		*/
		override protected function cleanUp():void {
			super.cleanUp();
			_noiseImage.dispose();
			_noiseImage = null;
			_fade = null;
		}
	
		/**
		* @description  Begins the transition.
		*/
		override public function start():void {
			super.start();
			_fade = new FadeTransition();
			_fade.clip = _noiseHolder;
			_fade.type = ((type == TransitionType.IN) ? TransitionType.OUT : TransitionType.IN);
			_fade.easeFunction = easeFunction;
			_fade.time = time;
			_fade.start();
		}
		
	}
	
}